package wicketforge.converter;

import java.awt.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.*;

import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import wicketforge.Constants;
import wicketforge.converter.dialog.RegexPathConverterDialog;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.SimpleTextAttributes;

public class RegexPathConverter extends BasePathConverter {

	private static final String PATTERN = "pattern";
	private static final String REPLACEMENT = "replacement";

	private String patter = "";
	private String replacement = "";
	private Pattern regExPattern;

	@Override
	public String convert(final String valueToReplace) {
		Matcher matcher = regExPattern.matcher(valueToReplace);
		if (matcher.find()) {
			return matcher.replaceAll(replacement);
		}
		return valueToReplace;
	}

	@Override
	public Icon getIcon() {
		return Constants.REGEX;
	}

	@Override
	public boolean openEditDialog(@NotNull final Component parent) {
		RegexPathConverterDialog dialog = new RegexPathConverterDialog(parent, this);
		return dialog.showAndGet();
	}

	@Override
	protected void renderInternal(@NotNull final ColoredListCellRenderer listCellRenderer) {
		listCellRenderer.append("\t\t\t\tMatcher: " + getPatter(), SimpleTextAttributes.GRAY_ATTRIBUTES, null);
		listCellRenderer.append("\t\t\t\tReplacement: " + getReplacement(), SimpleTextAttributes.GRAY_ATTRIBUTES, null);
		listCellRenderer.setToolTipText("Regularexpression Converter");
	}

	public void setPatter(final String patter) {
		if (!isModified()) {
			setModified(!patter.equals(this.patter));
		}
		this.patter = patter;
		regExPattern = Pattern.compile(patter);
	}

	@NotNull
	public String getPatter() {
		return patter;
	}

	public void setReplacement(final String replacement) {
		if(!isModified()) {
			setModified(!replacement.equals(this.replacement));
		}
		this.replacement = replacement;
	}

	@NotNull
	public String getReplacement() {
		return replacement;
	}

	@Nullable
	public Pattern getRegExPattern() {
		return regExPattern;
	}

	@Override
	protected void writeToConfigurationInternal(final Element configuration) {
		configuration.setAttribute(PATTERN, patter);
		configuration.setAttribute(REPLACEMENT, replacement);
	}

	@Override
	protected void readFromConfigurationInternal(final Element configuration) {
		setPatter(configuration.getAttributeValue(PATTERN));
		setReplacement(configuration.getAttributeValue(REPLACEMENT));
	}
}
